package com.datastructures2.sort;

/**
 * @author MaoLin Wang
 * @date 2020/4/1121:44
 */
public class MinPQ {

    public static <T extends Comparable<? super T>> void sort(T[] arr) {
        for (int i = arr.length / 2; i >= 0; i--) {
            perToDown(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            swap(arr, i, 0);
            perToDown(arr, 0, i);
        }
    }

    private static <T extends Comparable<? super T>> void swap(T[] arr, int i, int j) {
        T temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static <T extends Comparable<? super T>> void perToDown(T[] arr, int p, int length) {
        int child;
        T temp;
        for (temp = arr[p]; leftChild(p) < length; p = child) {
            child = leftChild(p);

            if (child != length - 1 && arr[child].compareTo(arr[child + 1]) < 0) {
                child++;
            }
            if (arr[child].compareTo(temp) > 0) {
                arr[p] = arr[child];
            }
        }
        arr[p] = temp;
    }

    private static int leftChild(int p) {
        return p * 2 + 1;
    }

    public static <T extends Comparable<? super T>> void sortMax(T[] arr) {
        for (int i = arr.length / 2; i >= 0; i--) {
            perToMinDown(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            swap(arr, 0, i);
            perToMinDown(arr, 0, i);
        }
    }

    /**
     * 小顶堆下滤
     *
     * @param arr
     * @param i
     * @param length
     * @param <T>
     */
    private static <T extends Comparable<? super T>> void perToMinDown(T[] arr, int i, int length) {
        int child;

        T temp;
        for (temp = arr[i]; leftChild(i) < length; i = child) {
            child = leftChild(i);

            if (child != length - 1 && arr[child].compareTo(arr[child + 1]) > 0) {
                child++;
            }

            if (arr[child].compareTo(temp) < 0) {
                arr[i] = arr[child];
            }


        }
        arr[i] = temp;

    }

    public static void main(String[] args) {
        Integer[] array = new Integer[10];
        for (int i = 0; i < 10; i++) {
            array[i] = (int) (Math.random() * 100);
        }
        sortMax(array);
        for (int i : array) {
            System.out.println(i);
        }
    }

}
